package com.bhp.security.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bhp.security.entity.UserAuth;
import com.bhp.security.service.RoleService;
import com.bhp.security.service.UserAuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * @ClassName UserService
 * @Description 实现security的UserDetailsService
 * @Author 包海鹏
 * @Date 2020/4/11 13:36
 * @Version 1.0
 **/
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserAuthService userAuthService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        QueryWrapper<UserAuth> qw = new QueryWrapper<>();
        qw.eq("c_name", name);
        UserAuth user = userAuthService.getOne(qw);
        if (user == null) {
            throw new UsernameNotFoundException("账户不存在！");
        }
        Auth auth = new Auth();
        BeanUtils.copyProperties(user, auth);
        auth.setRoles(roleService.getRolesByUserId(user.getId()));
        return auth;
    }
}
